/* Media Element Syncer, https://github.com/tjenkinson/media-element-syncer */
/*
MIT License

Copyright (c) 2019 Tom Jenkinson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 */
parcelRequire = (function (e, t, i, r) {
	var n,
		o = "function" == typeof parcelRequire && parcelRequire,
		s = "function" == typeof require && require;
	function a(i, r) {
		if (!t[i]) {
			if (!e[i]) {
				var n = "function" == typeof parcelRequire && parcelRequire;
				if (!r && n) return n(i, !0);
				if (o) return o(i, !0);
				if (s && "string" == typeof i) return s(i);
				var u = new Error("Cannot find module '" + i + "'");
				throw ((u.code = "MODULE_NOT_FOUND"), u);
			}
			(h.resolve = function (t) {
				return e[i][1][t] || t;
			}),
				(h.cache = {});
			var c = (t[i] = new a.Module(i));
			e[i][0].call(c.exports, h, c, c.exports, this);
		}
		return t[i].exports;
		function h(e) {
			return a(h.resolve(e));
		}
	}
	(a.isParcelRequire = !0),
		(a.Module = function (e) {
			(this.id = e), (this.bundle = a), (this.exports = {});
		}),
		(a.modules = e),
		(a.cache = t),
		(a.parent = o),
		(a.register = function (t, i) {
			e[t] = [
				function (e, t) {
					t.exports = i;
				},
				{},
			];
		});
	for (var u = 0; u < i.length; u++)
		try {
			a(i[u]);
		} catch (e) {
			n || (n = e);
		}
	if (i.length) {
		var c = a(i[i.length - 1]);
		"object" == typeof exports && "undefined" != typeof module
			? (module.exports = c)
			: "function" == typeof define && define.amd
			? define(function () {
					return c;
			  })
			: (this.MediaElementSyncer = c);
	}
	if (((parcelRequire = a), n)) throw n;
	return a;
})(
	{
		xiRv: [
			function (e, t, i) {
				"use strict";
				function r(e, t) {
					for (var i = 0; i < t.length; i++) {
						var r = t[i];
						(r.enumerable = r.enumerable || !1), (r.configurable = !0), "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r);
					}
				}
				Object.defineProperty(i, "__esModule", { value: !0 }), (i.MediaElementSyncer = void 0);
				var n = ["play", "pause", "seeking", "seeked", "playing", "stalled"],
					o = (function () {
						function e(t) {
							var i = this,
								r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {},
								n = r.refreshInterval,
								o = void 0 === n ? 200 : n,
								s = r.correctionTime,
								a = void 0 === s ? 500 : s,
								u = r.seekThreshold,
								c = void 0 === u ? 1e3 : u;
							!(function (e, t) {
								if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function");
							})(this, e),
								(this._source = t),
								(this._children = []),
								(this._updateTimer = null),
								(this._refreshInterval = o),
								(this._correctionTime = a / 1e3),
								(this._seekThreshold = c / 1e3),
								(this._config = new Map());
							var h = !1;
							this._eventHandler = function () {
								h ||
									((h = !0),
									window.setTimeout(function () {
										(h = !1), i._update();
									}, 0));
							};
						}
						var t, i, o;
						return (
							(t = e),
							(i = [
								{
									key: "addChild",
									value: function (e) {
										var t = (arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}).offset,
											i = void 0 === t ? 0 : t;
										-1 === this._children.indexOf(e) &&
											(this._children.length || this._addEventListeners(this._source), this._config.set(e, { offset: i }), this._children.push(e), this._addEventListeners(e), this._update());
									},
								},
								{
									key: "removeChild",
									value: function (e) {
										var t = this._children.indexOf(e);
										t >= 0 &&
											(this._config.delete(e),
											this._removeEventListeners(e),
											this._children.splice(t, 1),
											this._children.length || (this._updateTimer && (window.clearTimeout(this._updateTimer), (this._updateTimer = null)), this._removeEventListeners(this._source)));
									},
								},
								{
									key: "_update",
									value: function () {
										var e = this;
										if ((this._updateTimer && window.clearTimeout(this._updateTimer), this._children.length)) {
											var t = this._source.currentTime,
												i = this._source.playbackRate;
											this._children.forEach(function (r) {
												try {
													var n = e._config.get(r),
														o = t + n.offset / 1e3,
														s = e._source.paused || e._source.ended || o < 0 || o >= r.duration,
														a = o - r.currentTime,
														u = Math.max(0, ((a + e._correctionTime) / e._correctionTime) * i);
													s !== r.paused && (s ? r.pause() : r.play()), s || u < 0 || Math.abs(a) >= e._seekThreshold ? ((r.currentTime = o), (r.playbackRate = i)) : (r.playbackRate = u);
												} catch (e) {
													window.setTimeout(function () {
														throw e;
													}, 0);
												}
											}),
												(this._updateTimer = window.setTimeout(function () {
													return e._update();
												}, this._refreshInterval));
										}
									},
								},
								{
									key: "_addEventListeners",
									value: function (e) {
										var t = this;
										n.forEach(function (i) {
											return e.addEventListener(i, t._eventHandler);
										});
									},
								},
								{
									key: "_removeEventListeners",
									value: function (e) {
										var t = this;
										n.forEach(function (i) {
											return e.removeEventListener(i, t._eventHandler);
										});
									},
								},
							]) && r(t.prototype, i),
							o && r(t, o),
							e
						);
					})();
				i.MediaElementSyncer = o;
			},
			{},
		],
	},
	{},
	["xiRv"]
);
/*
 * nPlayer: NX (NeXt), the MSE-free player.
 * v1.3-NX is not compatible with legacy code. (pre 1.3 branch)
 *
 * This is a rewrite of nPlayer 1.2.1.
 * Changelog:
 * 1.3.1:
 * - Update lazy backend code.
 * - Added optional settings argument.
 */
if (!window.sleep) {
	window.sleep = function (ms) {
		var unixtime_ms = new Date().getTime();
		while (new Date().getTime() < unixtime_ms + ms) {}
	};
}
if (!window.base64Encode) {
	window.base64Encode = function (str) {
		try {
			return btoa(
				encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
					return String.fromCharCode(parseInt(p1, 16));
				})
			);
		} catch (ex) {
			return btoa(str);
		}
	};
}
if (!Math.average) {
	Math.average = function () {
		if (arguments.length == 0) {
			return 0;
		} else {
			if (arguments.length == 1 && Array.isArray(arguments[0])) {
				var n = 0;
				for (var i = 0; i < arguments[0].length; i++) {
					n += arguments[0][i];
				}
				return n / arguments[0].length;
			} else {
				var n = 0;
				for (var i = 0; i < arguments.length; i++) {
					n += arguments[i];
				}
				return n / arguments.length;
			}
		}
	};
}
window.nPlayerNXCore = {
	/**
	 * Currently tested MediaController browsers:
	 * BB10/WebKit: Broken??
	 */
	ALLOW_NATIVE_SYNC: true, // This seems to sort of work, but is deprecated.
	ALLOW_LAZY_SYNC: false,
	hasAnimationFrames: function () {
		return typeof requestAnimationFrame === "function";
	},
	getBackgroundChangeEventName: function () {
		if (typeof document.hidden !== "undefined") {
			return "visibilitychange";
		} else if (typeof document.msHidden !== "undefined") {
			return "msvisibilitychange";
		} else if (typeof document.webkitHidden !== "undefined") {
			return "webkitvisibilitychange";
		} else {
			return "hidden";
		}
	},
	backgroundPlaybackSupported: function () {
		try {
			return typeof window.chrome !== "object" && typeof window.chrome.runtime !== "object" && typeof window.chrome.csi !== "function";
		} catch (e) {
			return true;
		}
	},
	syncMethod: {
		/*
		 * NATIVE is deprecated, with planned removal in 1.4-NX.
		 */
		NATIVE: -1,
		PERFECT_SYNC_NEXT: 1,
		LITE_SYNC_NEXT: 2,
		PERFECT_SYNC_OLD: 3,
		LITE_SYNC_OLD: 4,
		LEGACY_SYNC: 5,
		PERFECT_SYNC2: 10, // BETA
		getSyncMethod: function () {
			if (typeof MediaController !== "undefined" && nPlayerNXCore.ALLOW_NATIVE_SYNC) {
				return nPlayerNXCore.syncMethod.NATIVE;
			}
			if (nPlayerNXCore.hasAnimationFrames()) {
				// TODO: Differ between Perfect and Lite Sync. (Also differ between NEW and OLD variants)
				if (typeof InstallTrigger !== "undefined") {
					/* Firefox path */
					if (!!window.Symbol && typeof Symbol.match !== "undefined" && typeof Symbol.species !== "undefined") {
						return nPlayerNXCore.syncMethod.PERFECT_SYNC_NEXT;
					} else {
						console.warn("[nPlayerNX] Detected legacy browser, falling back to LITE_SYNC...");
						return nPlayerNXCore.syncMethod.LITE_SYNC_NEXT;
					}
				}
				try {
					if (typeof window.chrome === "object" && typeof window.chrome.loadTimes === "function" && typeof window.chrome.csi === "function") {
						return nPlayerNXCore.syncMethod.PERFECT_SYNC_OLD;
					} else {
						return nPlayerNXCore.syncMethod.PERFECT_SYNC_NEXT;
					}
				} catch (e) {
					return nPlayerNXCore.syncMethod.PERFECT_SYNC_OLD;
				}
			} else {
				return nPlayerNXCore.syncMethod.LEGACY_SYNC;
			}
		},
		getDesyncLimit: function (id) {
			if (id == -1) {
				return 10;
			} else if (id == 1) {
				return 180;
			} else if (id == 2) {
				return 270;
			} else if (id == 3) {
				return 240;
			} else if (id == 4) {
				return 260;
			} else if (id == 10) {
				return 100;
			} else {
				return 380;
			}
		},
	},
};
window.nPlayerNX = function (mainPlayer, audioPlayer, settings) {
	settings = settings || {
		FORCE_ENABLE_NATIVE_SYNC: false,
		FORCE_ENABLE_LAZY_SYNC: false,
	};
	function isPlaying() {
		return !mainPlayer.paused && !audioPlayer.paused;
	}
	const USE_ANIMATION_FRAMES = nPlayerNXCore.hasAnimationFrames();
	const USE_DIRECT_SYNC = "requestVideoFrameCallback" in mainPlayer;
	var syncMethod = settings.FORCE_ENABLE_NATIVE_SYNC ? nPlayerNXCore.syncMethod.NATIVE : nPlayerNXCore.syncMethod.getSyncMethod();
	var native_controller = null;
	if (syncMethod === nPlayerNXCore.syncMethod.NATIVE) {
		mainPlayer.setAttribute("mediagroup", "__nplayernx_compat");
		audioPlayer.setAttribute("mediagroup", "__nplayernx_compat");
		mainPlayer.removeAttribute("autoplay");
		audioPlayer.removeAttribute("autoplay");
		native_controller = new window.MediaController();
		mainPlayer.autoplay = false;
		audioPlayer.autoplay = false;
		mainPlayer["controller"] = native_controller;
		audioPlayer["controller"] = native_controller;
		console.debug("NATIVE_SYNC_CONTROLLER: ", native_controller);
	}
	const IS_CHROME = !nPlayerNXCore.backgroundPlaybackSupported();
	const USE_FAST_SYNC = "fastSeek" in mainPlayer && "fastSeek" in audioPlayer;
	const USE_LAZY_SYNC = nPlayerNXCore.ALLOW_LAZY_SYNC || settings.FORCE_ENABLE_LAZY_SYNC;
	const ENABLE_NEW_DESYNC_CHECK_LOGIC = true;
	var isSeeking = false;
	var debugging = false;
	if (!USE_LAZY_SYNC) {
		var bak = false;
		function hasPIP() {
			if (!("pictureInPictureElement" in document)) return false;
			return document.pictureInPictureElement !== null;
		}
		function __sync() {
			if (syncMethod === nPlayerNXCore.syncMethod.NATIVE) {
				return;
			}
			if (mainPlayer.paused) mainPlayer.play();
			if (audioPlayer.paused) audioPlayer.play();
			const mt = mainPlayer.currentTime;
			const at = audioPlayer.currentTime;
			const diff = nPlayerNXCore.syncMethod.getDesyncLimit(syncMethod) / 1000 + (mt - at);
			if (USE_FAST_SYNC) {
				if (diff > 0) {
					mainPlayer.fastSeek(audioPlayer.currentTime);
					audioPlayer.fastSeek(mainPlayer.currentTime + diff);
				} else {
					mainPlayer.fastSeek(audioPlayer.currentTime + diff);
					audioPlayer.fastSeek(mainPlayer.currentTime);
				}
			} else {
				mainPlayer.currentTime = audioPlayer.currentTime = mainPlayer.currentTime + diff;
			}
		}
		document.addEventListener(nPlayerNXCore.getBackgroundChangeEventName(), function () {
			const prev = bak;
			bak = document.hidden && !hasPIP();
			if (syncMethod === nPlayerNXCore.syncMethod.NATIVE) {
				return;
			}
			if (IS_CHROME && isPlaying() && mainPlayer.currentTime > 1 && audioPlayer.currentTime > 1) {
				if (!document.hidden && !hasPIP()) {
					try {
						if (isDesynced()) {
							if (USE_DIRECT_SYNC) {
								mainPlayer.requestVideoFrameCallback(__sync);
							} else if (USE_ANIMATION_FRAMES) {
								window.requestAnimationFrame(__sync);
							} else {
								__sync();
							}
						}
					} catch (e) {}
				} else {
					try {
						if (!hasPIP()) mainPlayer.pause();
						audioPlayer.play();
					} catch (e) {}
				}
			}
		});
		function isDesynced() {
			if (syncMethod === nPlayerNXCore.syncMethod.NATIVE) {
				return false;
			}
			if (IS_CHROME && document.hidden && !hasPIP()) {
				if (debugging) {
					console.debug("isSynced(): Skipped check -> ELEMENT_IS_HIDDEN_CHROME");
				}
				return true;
			}
			if (isSeeking) isSeeking = false;
			if (mainPlayer.currentTime < 0.3 && audioPlayer.currentTime < 0.3) {
				if (debugging) {
					console.debug("isSynced(): Skipped check -> ELEMENT_WARMUP_PERIOD");
				}
				return false;
			}
			if (mainPlayer.duration - mainPlayer.currentTime < 1 && audioPlayer.duration - audioPlayer.currentTime < 1) {
				if (debugging) {
					console.debug("isSynced(): Skipped check -> ELEMENT_END_OF_MEDIA");
				}
				return false;
			}
			const mt = mainPlayer.currentTime;
			const at = audioPlayer.currentTime;
			if (ENABLE_NEW_DESYNC_CHECK_LOGIC) {
				return Math.abs(mt - at) > nPlayerNXCore.syncMethod.getDesyncLimit(syncMethod) / 1000;
			} else {
				var diff = mt - at;
				if (diff < 0) {
					diff /= -1;
				}
				diff *= 1000;
				return diff > nPlayerNXCore.syncMethod.getDesyncLimit(syncMethod) && mt !== at;
			}
		}
		function isInBackground() {
			if (!IS_CHROME) {
				return false;
			}
			return bak;
		}
		var inv =
			native_controller !== null
				? null
				: window.setInterval(function () {
						try {
							if (isPlaying()) {
								function _sync() {
									if (isDesynced()) {
										/* && !isSeeking */
										const at = audioPlayer.currentTime;
										const vt = mainPlayer.currentTime;
										if (debugging) {
											console.debug("interval_check: Desync found! Synchronising. [diff: " + (vt - at) + "]");
										}
										isSeeking = true;
										if (USE_FAST_SYNC) {
											audioPlayer.fastSeek(mainPlayer.currentTime);
										} else {
											audioPlayer.currentTime = mainPlayer.currentTime;
										}
									}
								}
								if (USE_DIRECT_SYNC) {
									mainPlayer.requestVideoFrameCallback(_sync);
								} else if (USE_ANIMATION_FRAMES) {
									window.requestAnimationFrame(_sync);
								} else {
									_sync();
								}
							}
						} catch (e) {
							console.error(e);
						}
				  }, 1000 / 45);
		mainPlayer.onplay = function () {
			if (debugging) {
				console.debug("mainPlayer::onPlay");
			}
			try {
				if (native_controller !== null) {
					native_controller.play();
				} else {
					audioPlayer.play();
				}
			} catch (e) {}
		};
		mainPlayer.onpause = function () {
			if (debugging) {
				console.debug("mainPlayer::onPause");
			}
			try {
				if (native_controller !== null) {
					native_controller.pause();
				} else {
					if (!document.hidden && !IS_CHROME) {
						mainPlayer.pause();
					} else if (!document.hidden && IS_CHROME) {
						mainPlayer.pause();
					} else {
						mainPlayer.play();
					}
					audioPlayer.pause();
				}
			} catch (e) {}
		};
		mainPlayer.onended = function () {
			if (mainPlayer.loop) {
				try {
					if (native_controller !== null) {
						native_controller.play();
					} else {
						mainPlayer.play();
						audioPlayer.play();
					}
				} catch (e) {
					console.error(e);
				}
			}
		};
		if (native_controller !== null) {
			mainPlayer.onseeking = function () {
				isSeeking = true;
			};
			mainPlayer.onseeked = function (c) {
				if (isDesynced()) {
					if (debugging) {
						console.debug(c);
					}
					const at = audioPlayer.currentTime;
					const vt = mainPlayer.currentTime;
					if (at > 2 && at !== vt) {
						if (debugging) {
							console.debug("onseeked: Desync found! Synchronising.");
						}
						function _s() {
							if (at > vt) {
								if (USE_FAST_SYNC) {
									audioPlayer.fastSeek(mainPlayer.currentTime);
								} else {
									audioPlayer.currentTime = mainPlayer.currentTime;
								}
							} else {
								audioPlayer.currentTime = mainPlayer.currentTime = audioPlayer.currentTime = mainPlayer.currentTime; // [internal screaming] (p.s: yes i know you can shorten this.)
							}
							if (mainPlayer.paused) {
								try {
									mainPlayer.play();
								} catch (e) {}
							}
							if (audioPlayer.paused) {
								try {
									audioPlayer.play();
								} catch (e) {}
							}
						}
						if (USE_DIRECT_SYNC) {
							mainPlayer.requestVideoFrameCallback(function () {
								_s();
							});
						} else if (USE_ANIMATION_FRAMES) {
							window.requestAnimationFrame(function () {
								_s();
							});
						} else {
							_s();
						}
						isSeeking = false;
						try {
							mainPlayer.play();
						} catch (e) {}
					} else {
						isSeeking = false;
					}
				} else {
					isSeeking = false;
				}
			};
		}
	} else {
		const syncInstance = new MediaElementSyncer.MediaElementSyncer(mainPlayer);
		syncInstance.addChild(audioPlayer, {
			refreshInterval: nPlayerNXCore.syncMethod.getDesyncLimit(syncMethod) + 50,
			seekThreshold: 650,
		});
	}
	const n = {
		version: nPlayerNX.versionString,
		play: function () {
			try {
				if (native_controller !== null) {
					native_controller.play();
				} else {
					mainPlayer.play();
					audioPlayer.play();
				}
			} catch (e) {}
		},
		applySource: function (video, audio) {
			const video_time = mainPlayer.currentTime;
			const audio_time = mainPlayer.currentTime;
			mainPlayer.src = video;
			audioPlayer.src = audio;
			try {
				if (native_controller !== null) {
					native_controller.play();
				} else {
					mainPlayer.play();
					audioPlayer.play();
				}
				if (native_controller == null && video_time >= 1 && audio_time >= 1) {
					if (USE_ANIMATION_FRAMES) {
						window.requestAnimationFrame(function () {
							if (USE_FAST_SYNC) {
								mainPlayer.fastSeek(video_time);
								audioPlayer.fastSeek(audio_time);
							} else {
								mainPlayer.currentTime = video_time;
								audioPlayer.currentTime = audio_time;
							}
						});
					} else {
						if (USE_FAST_SYNC) {
							mainPlayer.fastSeek(video_time);
							audioPlayer.fastSeek(audio_time);
						} else {
							mainPlayer.currentTime = video_time;
							audioPlayer.currentTime = audio_time;
						}
					}
				}
			} catch (e) {}
		},
		difference: function () {
			try {
				var diff = mainPlayer.currentTime - audioPlayer.currentTime;
				if (diff < 0) {
					diff /= -1;
				}
				diff *= 1000;
				return diff;
			} catch (e) {
				return -1;
			}
		},
		needsToSync: function () {
			return isDesynced();
		},
		getSyncMode: function () {
			return syncMethod;
		},
		isDebug: function () {
			return debugging;
		},
		setDebugMode: function (value) {
			if (typeof value !== "boolean") {
				throw new Error("nPlayer: Value must be a boolean!");
			}
			debugging = value;
		},
		seek: function (time) {
			if (typeof time !== "number") {
				throw new Error("nPlayer: This isn't a number!");
			}
			if (native_controller !== null) {
				native_controller.currentTime = time;
			} else {
				mainPlayer.currentTime = audioPlayer.currentTime = time; // TODO: Verify if fastSeek() is a good idea here.
			}
		},
		getTime: function () {
			return (mainPlayer.currentTime + audioPlayer.currentTime) / 2;
		},
		telemetry: {
			supportsDirectSync: USE_DIRECT_SYNC,
			supportsAnimationSync: USE_ANIMATION_FRAMES,
			supportsFastSync: USE_FAST_SYNC,
			requiresBlinkWorkaround: IS_CHROME,
			useNewSyncCalcLogic: ENABLE_NEW_DESYNC_CHECK_LOGIC,
			usesLazySync: USE_LAZY_SYNC,
			nativeController: native_controller,
		},
	};
	Object.freeze(n);
	return n;
};
nPlayerNX.version = "1.3.1";
nPlayerNX.branch = "NeXt";
nPlayerNX.versionString = "1.3-NX";
